package com.bqtv.sport.dialog

import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.text.TextUtils
import android.text.method.ScrollingMovementMethod
import android.view.LayoutInflater
import android.view.View
import android.widget.FrameLayout
import androidx.core.content.FileProvider
import com.bqtv.sport.R
import com.bqtv.sport.app.AppConfig
import com.bqtv.sport.databinding.UpdateDialogBinding
import com.hjq.base.BaseDialog
import com.hjq.base.action.AnimAction
import com.hjq.http.EasyHttp
import com.hjq.http.listener.OnDownloadListener
import com.hjq.http.model.HttpMethod
import com.hjq.permissions.OnPermissionCallback
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import com.hjq.toast.Toaster
import java.io.File

/**
 *    desc   : 升级对话框
 */
class UpdateDialog {

    class Builder(context: Context) : BaseDialog.Builder<Builder>(context) {
        var binding: UpdateDialogBinding = UpdateDialogBinding.inflate(
            LayoutInflater.from(context),
            FrameLayout(context),
            false
        )

        /** Apk 文件 */
        private var apkFile: File? = null

        /** 下载地址 */
        private var downloadUrl: String? = null

        /** 文件 MD5 */
        private var fileMd5: String? = null

        /** 是否强制更新 */
        private var forceUpdate = false

        /** 当前是否下载中 */
        private var downloading = false

        /** 当前是否下载完毕 */
        private var downloadComplete = false

        init {
            setContentView(binding.root)
            setAnimStyle(AnimAction.ANIM_BOTTOM)
            setCancelable(false)
            setOnClickListener(binding.tvUpdateUpdate, binding.tvUpdateClose)

            // 让 TextView 支持滚动
            binding.tvUpdateContent.movementMethod = ScrollingMovementMethod()
        }

        /**
         * 设置版本名
         */
        fun setVersionName(name: CharSequence?): Builder = apply {
            binding.tvUpdateName.text = name
        }

        /**
         * 设置更新日志
         */
        fun setUpdateLog(text: CharSequence?): Builder = apply {
            binding.tvUpdateContent.text = text
            binding.tvUpdateContent.visibility = if (text == null) View.GONE else View.VISIBLE
        }

        /**
         * 设置强制更新
         */
        fun setForceUpdate(force: Boolean): Builder = apply {
            forceUpdate = force
            binding.tvUpdateClose.visibility = if (force) View.GONE else View.VISIBLE
            setCancelable(!force)
        }

        /**
         * 设置下载 url
         */
        fun setDownloadUrl(url: String?): Builder = apply {
            downloadUrl = url
        }

        /**
         * 设置文件 md5
         */
        fun setFileMd5(md5: String?): Builder = apply {
            fileMd5 = md5
        }

        override fun onClick(view: View) {
            if (view === binding.tvUpdateClose) {
                dismiss()
            } else if (view === binding.tvUpdateUpdate) {
                // 判断下载状态
                if (downloadComplete) {
                    if (apkFile!!.isFile) {
                        // 下载完毕，安装 Apk
                        installApk()
                    } else {
                        // 下载失败，重新下载
                        XXPermissions.with(getContext())
                            .permission(Permission.MANAGE_EXTERNAL_STORAGE)
//                            .permission(Permission.WRITE_EXTERNAL_STORAGE)
//                            .permission(Permission.REQUEST_INSTALL_PACKAGES)
                            .request(object : OnPermissionCallback {
                                override fun onGranted(
                                    permissions: MutableList<String>,
                                    allGranted: Boolean
                                ) {
                                    if (allGranted) {
                                        downloadApk()
                                    }
                                }
                            })
                    }
                } else if (!downloading) {
                    // 没有下载，开启下载
                    XXPermissions.with(getContext())
                        .permission(Permission.MANAGE_EXTERNAL_STORAGE)
//                        .permission(Permission.WRITE_EXTERNAL_STORAGE)
//                        .permission(Permission.REQUEST_INSTALL_PACKAGES)
                        .request(object : OnPermissionCallback {
                            override fun onGranted(
                                permissions: MutableList<String>,
                                allGranted: Boolean
                            ) {
                                if (allGranted) {
                                    downloadApk()
                                }
                            }
                        })
                }
            }
        }

        /**
         * 下载 Apk
         */
        private fun downloadApk() {
            // 设置对话框不能被取消
            setCancelable(false)
            if (TextUtils.isEmpty(downloadUrl) || !downloadUrl?.startsWith("http")!!) {
                Toaster.show("下载链接异常")
                return
            }
            // 创建要下载的文件对象
            apkFile = File(
                getContext().getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS),
                getString(R.string.app_name) + "_v" + binding.tvUpdateName.text.toString() + ".apk"
            )

            EasyHttp.download(getDialog())
                .method(HttpMethod.GET)
                .file(apkFile)
                .url(downloadUrl)
                .md5(fileMd5)
                .listener(object : OnDownloadListener {

                    override fun onDownloadStart(file: File?) {
                        // 标记为下载中
                        downloading = true
                        // 标记成未下载完成
                        downloadComplete = false
                        // 后台更新
                        binding.tvUpdateClose.visibility = View.GONE
                        // 显示进度条
                        binding.pbUpdateProgress.visibility = View.VISIBLE
                        binding.tvUpdateUpdate.setText(R.string.update_status_start)
                    }

                    override fun onDownloadEnd(file: File?) {
                        // 更新进度条
                        binding.pbUpdateProgress.progress = 0
                        binding.pbUpdateProgress.visibility = View.GONE
                        // 标记当前不是下载中
                        downloading = false
                        // 如果当前不是强制更新，对话框就恢复成可取消状态
                        if (!forceUpdate) {
                            setCancelable(true)
                        }
                    }

                    override fun onDownloadProgressChange(file: File?, progress: Int) {
                        binding.tvUpdateUpdate.text =
                            String.format(getString(R.string.update_status_running)!!, progress)
                        binding.pbUpdateProgress.progress = progress
                    }

                    override fun onDownloadSuccess(file: File?) {

                        binding.tvUpdateUpdate.setText(R.string.update_status_successful)
                        // 标记成下载完成
                        downloadComplete = true
                        // 安装 Apk
                        installApk()
                    }

                    override fun onDownloadFail(file: File?, throwable: Throwable?) {

                        binding.tvUpdateUpdate.setText(R.string.update_status_failed)
                        // 删除下载的文件
                        file?.delete()
                    }
                }).start()
        }

        /**
         * 安装 Apk
         */
        private fun installApk() {
            XXPermissions.with(getContext())
                .permission(Permission.REQUEST_INSTALL_PACKAGES)
                .request(object : OnPermissionCallback {
                    override fun onGranted(permissions: MutableList<String>, allGranted: Boolean) {
                        if (allGranted) {
                            getContext().startActivity(getInstallIntent())
                        }
                    }
                })
        }

        /**
         * 获取安装意图
         */
        private fun getInstallIntent(): Intent {
            val intent = Intent()
            intent.action = Intent.ACTION_VIEW
            val uri: Uri?
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                uri = FileProvider.getUriForFile(
                    getContext(),
                    AppConfig.getPackageName() + ".provider",
                    apkFile!!
                )
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
            } else {
                uri = Uri.fromFile(apkFile)
            }
            intent.setDataAndType(uri, "application/vnd.android.package-archive")
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            return intent
        }
    }
}